package com.cbb.admin.cbb;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewCompat;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.cbb.alipay.PayResult;
import com.cbb.net.Constant;
import com.cbb.utils.CropUtils;
import com.cbb.utils.ToastUtils;
import com.google.gson.Gson;
import com.gyf.barlibrary.BarHide;
import com.gyf.barlibrary.ImmersionBar;
import com.gyf.barlibrary.OnKeyboardListener;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends CheckPermissionsActivity {
    private String url; //gt.caibangw.com
    @BindView(R.id.webView)
    WebView webView;
    private WebSettings settings;
    //微信支付
    final protected IWXAPI msgApi = WXAPIFactory.createWXAPI(this, Constant.WX_APP_ID, false);
    protected PayReq req;
    protected StringBuffer sb;
    public static final String WX_PAY = "weixin_pay";

    private static final int SDK_PAY_FLAG = 1;
    private PaymentBroadCastReceive receive;
    private StringRequest stringRequest, yuerStringRequest, wxStringRequest, caimiStringRequest;
    private Gson gson;
    private RequestQueue requestQueue;
    public String mMobile;


    // 用于保存剪裁后图片的URI
    private Uri imageUri = CropUtils.buildSavedUri(this);
    // 用于保存拍照图片的URI
    private Uri imagePhotoUri = CropUtils.buildPhotoUri(this);
    private PopupWindow popupWindow;
    private static final int WRITE_PERMISSION = 0x01;
    private String headPicUrl;
    private String contacterEmail = "",memberId="",enterpriseName="";
    private static final int MY_PERMISSIONS_REQUEST_CAMERA = 6;
    private static final int MY_PERMISSIONS_REQUEST_GALLERY = 7;
    private static final int PHOTO_REQUEST_CAREMA = 0;
    private static final int PHOTO_REQUEST_GALLERY = 1;
    private static final int PHOTO_REQUEST_CUT = 2;
    private  String imgeString;
    private View mDecorView;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    /**
                     * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                     * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                     * docType=1) 建议商户依赖异步通知
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息

                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        ToastUtils.show(mContext, "支付成功！");
                       /* if (webView.canGoBack()) {
                            webView.goBack();
                        }*/
                    } else {
                        // 判断resultStatus 为非"9000"则代表可能支付失败
                        // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            ToastUtils.show(mContext, "支付结果确认中！");
                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            ToastUtils.show(mContext, "支付失败！");
                          /*  if (webView.canGoBack()) {
                                webView.goBack();
                            }*/
                        }
                    }
                    break;
                }
                default:
                    break;
            }
        }


    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        setStatus();
        ButterKnife.bind(this);
        initView();
        initWXPay();
    }

    private void setStatusBarUpperAPI19() {
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

        ViewGroup mContentView = (ViewGroup) findViewById(Window.ID_ANDROID_CONTENT);
        View statusBarView = mContentView.getChildAt(0);
        //移除假的 View
        if (statusBarView != null && statusBarView.getLayoutParams() != null &&
                statusBarView.getLayoutParams().height == getStatusBarHeight()) {
            mContentView.removeView(statusBarView);
        }
        //不预留空间
        if (mContentView.getChildAt(0) != null) {
            ViewCompat.setFitsSystemWindows(mContentView.getChildAt(0), false);
        }
    }

    private int getStatusBarHeight(){
        int result = 0;
        int resId = getResources().getIdentifier("status_bar_height","dimen","android");
        if(resId>0){
            result = getResources().getDimensionPixelSize(resId);
        }
        return result;
    }
    private void setStatusBarUpperAPI21() {
        Window window = getWindow();
        //设置透明状态栏,这样才能让 ContentView 向上
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

        //需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);

        ViewGroup mContentView = (ViewGroup) findViewById(Window.ID_ANDROID_CONTENT);
        View mChildView = mContentView.getChildAt(0);
        if (mChildView != null) {
            //注意不是设置 ContentView 的 FitsSystemWindows, 而是设置 ContentView 的第一个子 View . 使其不为系统 View 预留空间.
            ViewCompat.setFitsSystemWindows(mChildView, false);
        }
    }

    private void initWXPay() {
        //微信支付相关
        req = new PayReq();
        sb = new StringBuffer();
        msgApi.registerApp("wxd1b0a49fdff94083");
        requestQueue = Volley.newRequestQueue(this);
        registBroadCast();
    }

    private void registBroadCast() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(WX_PAY);
        receive = new PaymentBroadCastReceive();
        registerReceiver(receive, filter);
    }

    //接受微信的广播
    class PaymentBroadCastReceive extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getBooleanExtra("is_pay", false)) {
                //mySendBroadcast(PAY_RESULT_SUCCESS);
               /* new Handler().postDelayed(new Runnable() {
                    public void run() {
                        Intent intent = new Intent(MainActivity.this,
                                MainActivity.class);
                        intent.putExtra("selectPager", 1);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                    }
                }, 1500);*/
                ToastUtils.show(mContext, "支付成功！");
            } else {
                ToastUtils.show(mContext, "支付失败！");
            }
           /* if (webView.canGoBack()) {
                webView.goBack();
            }*/
        }
    }

    private void initView() {
        url = getIntent().getStringExtra("url");
        if(TextUtils.isEmpty(url)){
            url =Constant.HOME_PAGE;
        }
        settings = webView.getSettings();
        settings.setJavaScriptEnabled(true); //如果访问的页面中有Javascript，则WebView必须设置支持Javascript
        settings.setDomStorageEnabled(true);  //设置适应Html5 //重点是这个设置

         settings.setAllowFileAccess(true);
        // settings.setJavaScriptCanOpenWindowsAutomatically(true);
         settings.setSupportZoom(true); //支持缩放
        // settings.setBuiltInZoomControls(true); //支持手势缩放
         settings.setDisplayZoomControls(false); //是否显示缩放按钮
        // settings.setPluginState(WebSettings.PluginState.ON);
        // >= 19(SDK4.4)启动硬件加速，否则启动软件加速
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
            // webView.setLayerType(View.LAYER_TYPE_NONE, null);
            settings.setLoadsImagesAutomatically(true); //支持自动加载图片
        } else {
            webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
            settings.setLoadsImagesAutomatically(false);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        settings.setUseWideViewPort(true); //将图片调整到适合WebView的大小
        settings.setLoadWithOverviewMode(true); //自适应屏幕
        // webView.loadDataWithBaseURL(null, "","text/html", "utf-8",null);
        // settings.setSaveFormData(true);
        //  settings.setSupportMultipleWindows(true);
        // settings.setAppCacheEnabled(true);
        //    settings.setCacheMode(WebSettings.LOAD_DEFAULT); //优先使用缓存

        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        // settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //设置缓存

        //  webView.setHorizontalScrollbarOverlay(true);
        //  webView.setHorizontalScrollBarEnabled(false);
        webView.setOverScrollMode(View.OVER_SCROLL_NEVER); // 取消WebView中滚动或拖动到顶部、底部时的阴影
        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); // 取消滚动条白边效果
        // webView.requestFocus();
        //webView.addJavascriptInterface(new JsInterface(), "android");
        //   webView.addJavascriptInterface(new JsInteration(), "control");
        webView.addJavascriptInterface(new JsInterface(), "android");

       // webView.loadUrl(Constant.HOME_PAGE);
        webView.loadUrl(url);

        webView.setWebViewClient(new WebViewClient() {
            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //这里进行url拦截
                if (url != null && url.startsWith("http://gopay.com")) {
                    doOrderPay();
                } else if (url.startsWith("http://gorecharge.com")) {
                    doRecharge();
                } else if (url.startsWith("http://goplus.com")) {
                    plusBuy();
                    //tel:021-80270945
                } else if (url.startsWith("http://tel.com")) {
                  //  dealPhone(url.substring(url.indexOf(":") + 1, url.length()));
                    dealPhone();
                } else if (url.startsWith("http://photo.com")) {
                    exportPho();
                }
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                Log.v("urlurlurl", url);
               // webView.loadUrl("javascript:getUserAgen(" + "android" + ")");
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                Log.v("urlurlurlurl", url);
                webView.loadUrl("javascript:getUserAgen(" + "android" + ")");
                //webView.loadUrl("javascript:getUserAgen("+"android"+")");
               /* webView.evaluateJavascript("javascript:getUserAgen(iOS)", new ValueCallback<String>() {
                    @Override
                    public void onReceiveValue(String value) {
                        Log.v("urlurlurl", value);
                    }
                });*/
                /*webView.setLayerType(View.LAYER_TYPE_NONE, null);
                if (!settings.getLoadsImagesAutomatically()) {
                    settings.setLoadsImagesAutomatically(true);
                }*/
              /*  webView.setLayerType(View.LAYER_TYPE_NONE, null);
                if (!settings.getLoadsImagesAutomatically()) {
                    settings.setLoadsImagesAutomatically(true);
                }
                //  webView.loadUrl("javascript:getContent()");
                webView.evaluateJavascript("javascript:getContent()", new ValueCallback<String>() {
                    @Override
                    public void onReceiveValue(String value) {
                        //此处为 js 返回的结果
                        if (value != null) {
                            //  share_content = value;
                        }
                        Log.v("urlurlurl", value);
                    }
                });
                webView.evaluateJavascript("javascript:getThum()", new ValueCallback<String>() {
                    @Override
                    public void onReceiveValue(String value) {
                        //此处为 js 返回的结果
                        if (value != null) {
                            //   share_img = value;
                        }
                        Log.v("urlurlurlurl", value);
                    }
                });*/
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
            }
        });
    }

    /* =======================支付==============================*/
    String m, aliSign;
    JSONObject jsonData;

    /**
     * 订单支付
     */
    private void doOrderPay() {
        webView.evaluateJavascript("exportPay()", new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String s) {
                Log.v("dfasdfsdf", s.toString());
                pay(s);
            }
        });
    }

    /**
     * 充值
     */
    private void doRecharge() {
        webView.evaluateJavascript("exportRecharge()", new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String s) {
                Log.v("dfasdfsdf", s.toString());
                pay(s);
            }
        });
    }

    /**
     * plus会员购买
     */
    private void plusBuy() {
        webView.evaluateJavascript("exportPluspay()", new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String s) {
                pay(s);
            }
        });
    }

    /**
     * 拨打电话
     * @param
     */
    final public static int REQUEST_CODE_ASK_CALL_PHONE = 123;
    private void dealPhone() {
        webView.evaluateJavascript("exportTel()", new ValueCallback<String>() {
            @Override
            public void onReceiveValue(final String s) {
                Log.v("rrrrrrrrrrrrr", s);
                mMobile = s;
                //url.substring(url.indexOf(":") + 1, url.length())
                if (Build.VERSION.SDK_INT >= 23) {
                    int checkCallPhonePermission = ContextCompat.checkSelfPermission(mContext, Manifest.permission.CALL_PHONE);
                    if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CALL_PHONE}, REQUEST_CODE_ASK_CALL_PHONE);
                    } else {
                        callDirectly(mMobile);
                    }
                } else {
                    callDirectly(mMobile);
                }

                /*try {
                    new MaterialDialog.Builder(mContext)
                            .setTitle("拨打电话")
                            .setMessage(s)
                            .setPositiveButton(new MaterialDialog.OnClickListener() {
                                @Override
                                public boolean onClick(DialogInterface dialog, int which) {
                                    if (Build.VERSION.SDK_INT >= 23) {
                                        int checkCallPhonePermission = ContextCompat.checkSelfPermission(mContext, Manifest.permission.CALL_PHONE);
                                        if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                                            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CALL_PHONE}, REQUEST_CODE_ASK_CALL_PHONE);
                                            return false;
                                        } else {
                                            callDirectly(s);
                                        }
                                    } else {
                                        callDirectly(s);
                                    }
                                    return false;
                                }
                            })
                            //.setNeutralButton("不再提示", null)
                            .setNegativeButton(new MaterialDialog.OnClickListener() {
                                @Override
                                public boolean onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    return false;
                                }
                            }).show();


                } catch (Exception e) {
                    e.printStackTrace();
                }*/
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_ASK_CALL_PHONE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    callDirectly(mMobile);
                } else {
                    Toast.makeText(MainActivity.this, "CALL_PHONE Denied", Toast.LENGTH_SHORT)
                            .show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    private void callDirectly(String phone){
        Log.v("asdfsdfsd",phone);
        Intent intent = new Intent();
        intent.setAction("android.intent.action.CALL");
        intent.setData(Uri.parse("tel:" + phone));
        mContext.startActivity(intent);
    }
    /**
     * 上传头像
     */
    private void exportPho(){
        uploadHeadImage();
       /* webView.evaluateJavascript("exportPho()", new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String s) {

            }
        });*/
    }
    /**
     * 微信、支付宝支付
     * @param s
     */
    private void pay(String s){
        try {
            JSONArray array = new JSONArray(s);
            m  = (String) array.get(0);
            boolean isJson = array.get(1) instanceof JSONObject;
            if(isJson){
                jsonData = array.getJSONObject(1);
                aliSign = jsonData.getString("sign");
            }else{
                aliSign = (String) array.get(1);
            }

           /* for (int i = 0; i < array.length(); i++) {
                m  = (String) array.get(0);
                jsonData = array.getJSONObject(1);
            }*/
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if(m.equals("wx")){
            try {
                req.appId = jsonData.getString("appid");
                req.nonceStr = jsonData.getString("noncestr");
                req.packageValue = jsonData.getString("package");
                req.partnerId = jsonData.getString("partnerid");
                req.prepayId = jsonData.getString("prepayid");
                req.sign = jsonData.getString("sign");
                req.timeStamp = jsonData.getString("timestamp");
                // 调微信支付
                if(msgApi.isWXAppInstalled()&&msgApi.isWXAppSupportAPI()){
                    msgApi.sendReq(req);
                }else{
                    ToastUtils.show(mContext,"未安装微信,请修改支付方式或安装微信！");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }else if(m.equals("alipay")){
         /*   try {
                aliSign = jsonData.getString("sign");
            } catch (JSONException e) {
                e.printStackTrace();
            }*/
            Runnable payRunnable = new Runnable() {
                @Override
                public void run() {
                    // 构造PayTask 对象
                    PayTask alipay = new PayTask(MainActivity.this);
                    // 调用支付接口，获取支付结果
                    String result = alipay.pay(aliSign, true);
                    Message msg = new Message();
                    msg.what = SDK_PAY_FLAG;
                    msg.obj = result;
                    mHandler.sendMessage(msg);
                }
            };
            // 必须异步调用
            Thread payThread = new Thread(payRunnable);
            payThread.start();
        }
    }
    private class JsInterface {
        @JavascriptInterface  //这个注解一定要带上
        public void cacheclear() {

        }

        @JavascriptInterface
        public void userlocation() {


        }

    }


    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            if (webView.canGoBack()) {
                webView.goBack();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }


    /**
     * 上传头像
     */
    private void uploadHeadImage() {
        View view = LayoutInflater.from(this).inflate(R.layout.layout_popupwindow, null);
        TextView btnCarema = (TextView) view.findViewById(R.id.btn_camera);
        TextView btnPhoto = (TextView) view.findViewById(R.id.btn_photo);
        TextView btnCancel = (TextView) view.findViewById(R.id.btn_cancel);
        popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setBackgroundDrawable(getResources().getDrawable(android.R.color.transparent));
        popupWindow.setOutsideTouchable(true);
        View parent = LayoutInflater.from(this).inflate(R.layout.activity_main, null);
        popupWindow.showAtLocation(parent, Gravity.BOTTOM, 0, 0);
        //popupWindow在弹窗的时候背景半透明
        final WindowManager.LayoutParams params = getWindow().getAttributes();
        params.alpha = 0.5f;
        getWindow().setAttributes(params);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                params.alpha = 1.0f;
                getWindow().setAttributes(params);
            }
        });


        btnCarema.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ContextCompat.checkSelfPermission(MainActivity.this,
                        Manifest.permission.CAMERA)
                        != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(MainActivity.this,
                            new String[]{Manifest.permission.CAMERA},
                            MY_PERMISSIONS_REQUEST_CAMERA);
                } else {
                    takePhoto(popupWindow);
                }
            }
        });
        btnPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ContextCompat.checkSelfPermission(MainActivity.this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(MainActivity.this,
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            MY_PERMISSIONS_REQUEST_GALLERY);
                } else {
                    choosePhoto(popupWindow);
                }
            }
        });
    }
    private void takePhoto(PopupWindow popupWindow) {
        // 调用系统相机
        Intent intentCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //  intentCamera.addCategory(Intent.CATEGORY_DEFAULT);
        // 将拍照结果保存至imageUri中，不保留在相册中
        intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, imagePhotoUri);
        this.startActivityForResult(intentCamera, PHOTO_REQUEST_CAREMA);
        popupWindow.dismiss();
        Log.v("aaaaaaaaaa", imagePhotoUri.toString());

     /*   Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
        this.startActivityForResult(intent, PHOTO_REQUEST_CAREMA);
        popupWindow.dismiss();*/
    }

    private void choosePhoto(PopupWindow popupWindow) {
        // 调用系统相册
        Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
        photoPickerIntent.setType("image/*");
        photoPickerIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivityForResult(photoPickerIntent, PHOTO_REQUEST_GALLERY);
        popupWindow.dismiss();
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case PHOTO_REQUEST_GALLERY:
                if (resultCode == RESULT_OK) {
                    // 从相册选取成功后，需要从Uri中拿出图片的绝对路径，再调用剪切
                    Uri newUri = Uri.parse("file:///" + CropUtils.getPath(this, data.getData()));
                    if (newUri != null) {
                        CropUtils.cropImageUri(this, newUri, imageUri, 100, 100,
                                PHOTO_REQUEST_CUT);
                    } else {
                        ToastUtils.show(this, "没有得到相册图片");

                    }
                } else if (resultCode == RESULT_CANCELED) {
                    ToastUtils.show(this, "从相册选取取消");
                } else {
                    ToastUtils.show(this, "从相册选取失败");
                }
                break;
            case PHOTO_REQUEST_CAREMA:
                if (resultCode == RESULT_OK) {
                    // 从相机选取成功后，需要从Uri中拿出图片的绝对路径，再调用剪切
                    if (imagePhotoUri != null) {
                        CropUtils.cropImageUri(this, imagePhotoUri, imageUri, 100, 100,
                                PHOTO_REQUEST_CUT);
                    } else {
                        ToastUtils.show(this, "没有得到拍照图片");
                    }
                } else if (resultCode == RESULT_CANCELED) {
                    ToastUtils.show(this, "取消拍照");
                } else {
                    ToastUtils.show(this, "拍照失败");
                }
                break;
            case PHOTO_REQUEST_CUT:
                if (resultCode == RESULT_OK) {
                    setPicToView(data);
                   // uploadImage();
                } else if (resultCode == RESULT_CANCELED) {
                    ToastUtils.show(this, "取消剪切图片");
                } else {
                    ToastUtils.show(this, "剪切失败");
                }
                break;
            default:
                break;
        }
    }
    private void setPicToView(Intent picdata) {
        /*
         * Bundle bundle = picdata.getExtras(); if (bundle != null) { Bitmap
		 * photo = bundle.getParcelable("data"); Drawable drawable = new
		 * BitmapDrawable(photo); flag=true;
		 * cvAvatar.setImageDrawable(drawable); }
		 */
        // imageUri = data.getData();
        Bitmap bitmap = decodeUriBitmap(imageUri);
       // iv_photo_graph.setImageBitmap(bitmap);
        imgeString = getImageBase64(bitmap);
        Log.v("asdfsdfasdfasdf",imgeString);
        webView.loadUrl("javascript:exportPho("+imgeString+")");
       /* webView.evaluateJavascript("exportPho(" + imgeString +")", new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String s) {

            }
        });*/
    }

    private Bitmap decodeUriBitmap(Uri uri) {
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
            //  bitmap = BitmapFactory.decodeStream(new URL(file_url).openStream() );
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
        return bitmap;
    }

    private String getImageBase64(Bitmap bitmap) {
        // decode to bitmap
       // iv_photo_graph.buildDrawingCache();
       //  Bitmap bitmap = iv_photo_graph.getDrawingCache();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] bytes = baos.toByteArray();

        return Base64.encodeToString(bytes, Base64.DEFAULT);
    }

    @Override
    protected void onResume() {
        super.onResume();
        setStatus();
    }

    private void setStatus(){
        ImmersionBar.with(this)
                .transparentStatusBar()  //透明状态栏，不写默认透明色
                //.transparentNavigationBar()  //透明导航栏，不写默认黑色(设置此方法，fullScreen()方法自动为true)
                //.transparentBar()             //透明状态栏和导航栏，不写默认状态栏为透明色，导航栏为黑色（设置此方法，fullScreen()方法自动为true）
                //.statusBarColor(R.color.colorPrimary)     //状态栏颜色，不写默认透明色
               // .navigationBarColor(R.color.colorPrimary) //导航栏颜色，不写默认黑色
               // .barColor(R.color.colorPrimary)  //同时自定义状态栏和导航栏颜色，不写默认状态栏为透明色，导航栏为黑色
               // .statusBarAlpha(0.3f)  //状态栏透明度，不写默认0.0f
                //.navigationBarAlpha(0.4f)  //导航栏透明度，不写默认0.0F
                //.barAlpha(0.3f)  //状态栏和导航栏透明度，不写默认0.0f
                .statusBarDarkFont(true)   //状态栏字体是深色，不写默认为亮色
                .flymeOSStatusBarFontColor(R.color.black_de)  //修改flyme OS状态栏字体颜色
                //.fullScreen(true)      //有导航栏的情况下，activity全屏显示，也就是activity最下面被导航栏覆盖，不写默认非全屏
                //.hideBar(BarHide.FLAG_HIDE_BAR)  //隐藏状态栏或导航栏或两者，不写默认不隐藏
                .hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR)
                //.addViewSupportTransformColor(toolbar)  //设置支持view变色，可以添加多个view，不指定颜色，默认和状态栏同色，还有两个重载方法
                //.titleBar(view)    //解决状态栏和布局重叠问题，任选其一
                //.titleBarMarginTop(view)     //解决状态栏和布局重叠问题，任选其一
                //.statusBarView(view)  //解决状态栏和布局重叠问题，任选其一
                .fitsSystemWindows(true)    //解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
               // .supportActionBar(true) //支持ActionBar使用
               // .statusBarColorTransform(R.color.orange)  //状态栏变色后的颜色
               // .navigationBarColorTransform(R.color.orange) //导航栏变色后的颜色
                //.barColorTransform(R.color.orange)  //状态栏和导航栏变色后的颜色
               // .removeSupportView(toolbar)  //移除指定view支持
                //.removeSupportAllView() //移除全部view支持
               // .navigationBarEnable(true)   //是否可以修改导航栏颜色，默认为true
                .navigationBarWithKitkatEnable(true)  //是否可以修改安卓4.4和emui3.1手机导航栏颜色，默认为true
                .fixMarginAtBottom(true)   //已过时，当xml里使用android:fitsSystemWindows="true"属性时,解决4.4和emui3.1手机底部有时会出现多余空白的问题，默认为false，非必须
                //.addTag("tag")  //给以上设置的参数打标记
                //.getTag("tag")  //根据tag获得沉浸式参数
               // .reset()  //重置所以沉浸式参数
                .keyboardEnable(true)  //解决软键盘与底部输入框冲突问题，默认为false，还有一个重载方法，可以指定软键盘mode
                .keyboardMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)  //单独指定软键盘模式
                .setOnKeyboardListener(new OnKeyboardListener() {    //软键盘监听回调
                    @Override
                    public void onKeyboardChange(boolean isPopup, int keyboardHeight) {
                       // LogUtils.e(isPopup);  //isPopup为true，软键盘弹出，为false，软键盘关闭
                    }
                })
                .init();  //必须调用方可沉浸式
    }
}
